package com.my.study.net.transfer;

import com.my.study.io.StreamUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

/**
 * @author Carlos
 * @version 1.0
 * @Description 客户端 - 发送文件
 * @date 2021/7/3 22:03
 **/
@Slf4j(topic = "c.TCPFileUploadClient")
public class TCPFileUploadClient {

    public static void main(String[] args) throws IOException {
        Socket socket = new Socket(InetAddress.getLocalHost(), 8888);


        //=======================================将文件内容发送给服务端
        // 读取文件，并把文件内容暂存在字节数组中
        String path = "D:/file/ReentrantLock.png";
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(path));
        // 获取文件内容
        byte[] bytes = StreamUtils.streamToByteArray(bis);

        BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
        bos.write(bytes);
        // 设置写入数据的结束标记
        socket.shutdownOutput();

        //=======================================获取服务端发送的确定消息
        InputStream in = socket.getInputStream();
        String context = StreamUtils.streamToString(in);
        log.debug("context: {}", context);

        //关闭流
        in.close();
        bos.close();
        bis.close();
        socket.close();
    }
}
